const axios = require('axios');
const configLoader = require('../utils/config-loader');
const logger = require('../utils/logger');

class NapCatAPI {
    constructor() {
        this.config = null;
        this.client = null;
        this.initialized = false;
    }

    async initialize() {
        if (this.initialized) return;
        
        try {
            this.config = await configLoader.load();
            this.setupClient();
            this.initialized = true;
            logger.debug('NapCat API 客户端初始化完成');
        } catch (error) {
            logger.error('NapCat API 客户端初始化失败:', error);
            throw error;
        }
    }

    async ensureInitialized() {
        if (!this.initialized) {
            await this.initialize();
        }
    }

    setupClient() {
        this.client = axios.create({
            baseURL: this.config.napcat.baseUrl,
            timeout: this.config.napcat.timeout,
            headers: {
                'Content-Type': 'application/json'
            }
        });

        // 添加认证头
        if (this.config.napcat.token) {
            this.client.defaults.headers.common['Authorization'] = `Bearer ${this.config.napcat.token}`;
        }

        // 请求拦截器
        this.client.interceptors.request.use(
            (config) => {
                logger.debug(`API 请求: ${config.method?.toUpperCase()} ${config.url}`);
                return config;
            },
            (error) => {
                logger.error('API 请求错误:', error);
                return Promise.reject(error);
            }
        );

        // 响应拦截器
        this.client.interceptors.response.use(
            (response) => {
                return response.data;
            },
            (error) => {
                logger.error('API 响应错误:', {
                    url: error.config?.url,
                    method: error.config?.method,
                    status: error.response?.status,
                    message: error.message
                });
                return Promise.reject(error);
            }
        );
    }

    // 工具方法 - 检查响应是否成功
    isSuccess(response) {
        return response && response.status === 'ok';
    }

    // 工具方法 - 获取响应数据
    getData(response) {
        return response ? response.data : null;
    }

    // 工具方法 - 获取消息ID
    getMessageId(response) {
        return response && response.data ? response.data.message_id : null;
    }

    // 用户相关 API
    async getLoginInfo() {
        await this.ensureInitialized();
        return this.client.get('/get_login_info');
    }

    async getFriendList() {
        await this.ensureInitialized();
        return this.client.get('/get_friend_list');
    }

    async getGroupList() {
        await this.ensureInitialized();
        return this.client.get('/get_group_list');
    }

    // 消息相关 API
    async sendPrivateMessage(userId, message, autoEscape = false) {
        await this.ensureInitialized();
        return this.client.post('/send_private_msg', {
            user_id: userId,
            message: message,
            auto_escape: autoEscape
        });
    }

    async sendGroupMessage(groupId, message, autoEscape = false) {
        await this.ensureInitialized();
        return this.client.post('/send_group_msg', {
            group_id: groupId,
            message: message,
            auto_escape: autoEscape
        });
    }

    async sendMessage(messageType, id, message, autoEscape = false) {
        await this.ensureInitialized();
        return this.client.post('/send_msg', {
            message_type: messageType,
            [messageType === 'private' ? 'user_id' : 'group_id']: id,
            message: message,
            auto_escape: autoEscape
        });
    }

    // 消息撤回
    async deleteMessage(messageId) {
        await this.ensureInitialized();
        return this.client.post('/delete_msg', {
            message_id: messageId
        });
    }

    // 获取消息
    async getMessage(messageId) {
        await this.ensureInitialized();
        return this.client.post('/get_msg', {
            message_id: messageId
        });
    }

    // 获取转发消息
    async getForwardMessage(messageId) {
        await this.ensureInitialized();
        return this.client.post('/get_forward_msg', {
            message_id: messageId
        });
    }

    // 图片 OCR
    async ocrImage(image) {
        await this.ensureInitialized();
        return this.client.post('/ocr_image', {
            image: image
        });
    }

    // 群组管理
    async setGroupKick(groupId, userId, rejectAddRequest = false) {
        await this.ensureInitialized();
        return this.client.post('/set_group_kick', {
            group_id: groupId,
            user_id: userId,
            reject_add_request: rejectAddRequest
        });
    }

    async setGroupBan(groupId, userId, duration = 30 * 60) {
        await this.ensureInitialized();
        return this.client.post('/set_group_ban', {
            group_id: groupId,
            user_id: userId,
            duration: duration
        });
    }

    async setGroupWholeBan(groupId, enable = true) {
        await this.ensureInitialized();
        return this.client.post('/set_group_whole_ban', {
            group_id: groupId,
            enable: enable
        });
    }

    // 测试连接
    async testConnection() {
        try {
            await this.ensureInitialized();
            const result = await this.getLoginInfo();
            return {
                connected: this.isSuccess(result),
                userInfo: this.getData(result),
                config: {
                    baseUrl: this.config.napcat.baseUrl,
                    hasToken: !!this.config.napcat.token
                }
            };
        } catch (error) {
            return {
                connected: false,
                error: error.message
            };
        }
    }
}

// 创建实例并预初始化
const napcatAPI = new NapCatAPI();
napcatAPI.initialize().catch(error => {
    logger.error('NapCat API 预初始化失败:', error);
});

module.exports = napcatAPI;